package com.example.rss_reder;


import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.app.TabActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TabHost;
import android.widget.Toast;

@SuppressLint("HandlerLeak")
public class MainActivity extends TabActivity {
	MyAdapter adapter;
	ArrayList<List> data;
	DBAdapter db;

	String[] cat = {"종합","경제","정치","사회","국제","연예","스포츠","IT"};

	String[][] news_url = {
			{//한경
				"http://rss.hankooki.com/news/hk_main.xml"//종합
				,"http://rss.hankooki.com/news/hk_economy.xml"//경제
				,"http://rss.hankooki.com/news/hk_politics.xml"//정치
				,"http://rss.hankooki.com/news/hk_society.xml"//사회
				,"http://rss.hankooki.com/news/hk_world.xml"//국제
				,"http://rss.hankooki.com/news/hk_entv.xml"//연예
				,"http://rss.hankooki.com/news/hk_sports.xml"//스포츠
				,"http://rss.hankooki.com/news/hk_it_tech.xml"//IT
			},{//중앙
				"http://rss.joinsmsn.com/joins_news_list.xml"//종합
				,"http://rss.joinsmsn.com/joins_money_list.xml"//경제
				,"http://rss.joinsmsn.com/joins_politics_list.xml"//정치
				,"http://rss.joinsmsn.com/joins_life_list.xml"//사회
				,"http://rss.joinsmsn.com/joins_world_list.xml"//국제
				,"http://rss.joinsmsn.com/joins_star_list.xml"//연예
				,"http://rss.joinsmsn.com/joins_sports_list.xml"//스포츠
				,"http://rss.joinsmsn.com/joins_it_list.xml"//IT
			},{//조선
				"http://myhome.chosun.com/rss/www_section_rss.xml"//종합
				,"http://biz.chosun.com/site/data/rss/rss.xml"//경제
				,"http://www.chosun.com/site/data/rss/politics.xml"//정치
				,"http://www.chosun.com/site/data/rss/national.xml"//사회
				,"http://www.chosun.com/site/data/rss/international.xml"//국제
				,"http://www.chosun.com/site/data/rss/ent.xml"//연예
				,"http://www.chosun.com/site/data/rss/sports.xml"//스포츠
				,"http://myhome.chosun.com/rss/www_section_rss_16.xml"//IT
			},{//경향
				"http://www.khan.co.kr/rss/rssdata/total_news.xml"	//종합
				,"http://www.khan.co.kr/rss/rssdata/economy_news.xml"	//경제
				,"http://www.khan.co.kr/rss/rssdata/politic_news.xml"	//정치
				,"http://www.khan.co.kr/rss/rssdata/society_news.xml"	//사회
				,"http://www.khan.co.kr/rss/rssdata/kh_world.xml"	//국제
				,"http://www.khan.co.kr/rss/rssdata/kh_entertainment.xml"	//연예
				,"http://www.khan.co.kr/rss/rssdata/kh_sports.xml"	//스포츠
				,"http://www.khan.co.kr/rss/rssdata/it_news.xml"	//IT
			},{//매일
				"http://file.mk.co.kr/news/rss/rss_40300001.xml"	//종합
				,"http://file.mk.co.kr/news/rss/rss_30100041.xml"	//경제
				,"http://file.mk.co.kr/news/rss/rss_30200030.xml"	//정치
				,"http://file.mk.co.kr/news/rss/rss_50400012.xml"	//사회
				,"http://file.mk.co.kr/news/rss/rss_30300018.xml"	//국제
				,"http://file.mk.co.kr/news/rss/rss_30000023.xml"	//연예
				,"http://file.mk.co.kr/news/rss/rss_50600001.xml"	//스포츠
				,"http://file.mk.co.kr/news/rss/rss_50100032.xml"	//IT
			},{//동아
				"http://rss.donga.com/total.xml"	//종합
				,"http://rss.donga.com/economy.xml"	//경제
				,"http://rss.donga.com/politics.xml"	//정치
				,"http://rss.donga.com/national.xml"	//사회
				,"http://rss.donga.com/international.xml"	//국제
				,"http://rss.donga.com/culture.xml"	//연예
				,"http://rss.donga.com/sports.xml"	//스포츠
				,"http://rss.donga.com/science.xml"	//IT
			},{//한겨레
				"http://www.hani.co.kr/rss/"	//종합
				,"http://www.hani.co.kr/rss/economy/"	//경제
				,"http://www.hani.co.kr/rss/politics/"	//정치
				,"http://www.hani.co.kr/rss/society/"	//사회
				,"http://www.hani.co.kr/rss/international/"	//국제
				,"http://www.hani.co.kr/rss/culture/"	//연예
				,"http://www.hani.co.kr/rss/sports/"	//스포츠
				,"http://www.hani.co.kr/rss/science/" 	//IT
			}};


	ListView lv;
	Spinner s1, s2;
	int a, b;
	ArrayList<String> u;
	private final int DID = 0;
	private final int WHAT = 0;


	Handler handler = new Handler(){
		public void handleMessage(Message msg){
			switch (msg.what){
				case WHAT:
					lv = (ListView)findViewById(R.id.lv);; 
					lv.setAdapter(adapter);
					lv.setOnItemClickListener(new OnItemClickListener() {

						@Override
						public void onItemClick(AdapterView<?> arg0, View arg1,
								int arg2, long arg3) {
							// TODO Auto-generated method stub
							if(data.get(arg2).getLink()!=null){
								Intent i = new Intent(MainActivity.this, WebLink.class);
								i.putExtra("link", data.get(arg2).getLink());
								i.putExtra("date", data.get(arg2).getDate());
								i.putExtra("name", data.get(arg2).getName());
								i.putExtra("img", data.get(arg2).getImg());
								startActivity(i);
							}
						}
					});

					removeDialog(DID);
					break;
			}
		}
	};

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		menu.add(Menu.NONE, Menu.FIRST+1, Menu.NONE, "내 스크랩보기");
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		boolean a = false;
		Toast t;

		switch(item.getItemId()){
			case Menu.FIRST+1:
				t = Toast.makeText(MainActivity.this, "1", Toast.LENGTH_LONG);

			callList(2);
			t.show();
			a=true;
			break;
		}

		return (a || super.onOptionsItemSelected(item));
	}
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		db = new DBAdapter(MainActivity.this);

		TabHost tabhost= getTabHost();

		tabhost.addTab(tabhost.newTabSpec("first_tab").setIndicator("뉴스검색").setContent(R.id.first));
		tabhost.addTab(tabhost.newTabSpec("second_tab").setIndicator("카테고리").setContent(R.id.second));

		tabhost.setCurrentTab(0);

		s1 = (Spinner)findViewById(R.id.sp1);
		ArrayAdapter<CharSequence> a1 = ArrayAdapter.createFromResource(this, R.array.news, android.R.layout.simple_spinner_item);
		a1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		s1.setAdapter(a1);

		s2 = (Spinner)findViewById(R.id.sp2);
		ArrayAdapter<CharSequence> a2 = ArrayAdapter.createFromResource(this, R.array.category, android.R.layout.simple_spinner_item);
		a2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		s2.setAdapter(a2);

		s1.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				// TODO Auto-generated method stub
				a = arg2;
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
				Toast t = Toast.makeText(MainActivity.this, "언론사를 선택하여 주십시오.", Toast.LENGTH_LONG);
				t.show();
			}

		});

		s2.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				// TODO Auto-generated method stub
				b = arg2;
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
				Toast t = Toast.makeText(MainActivity.this, "카테고리를 선택하여 주십시오.", Toast.LENGTH_LONG);
				t.show();
			}

		});

		Button btn = (Button)findViewById(R.id.btn);

		btn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				EditText et = (EditText)findViewById(R.id.et);
				String su = et.getText().toString();
				String query = null;

				try {
					query = URLEncoder.encode(su, "utf-8");
				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				//종합
				//						u = "http://www.kmobile.co.kr/rss/all";
				//				Log.i("test",u);
				String url = "http://news.google.co.kr/news?q="+
						query+
						"&hl=ko&newwindow=1&prmd=imvnsul&bav=on.2,or.r_gc.r_pw.r_qf.&biw=1600&bih=809&um=1&ie=UTF-8&output=rss";
				u = new ArrayList<String>();
				u.add(url);
				callList(1);
			}
		});

		Button btn2 = (Button)findViewById(R.id.btn2);
		btn2.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				u = new ArrayList<String>();

				if(b==0){
					for(int i=0;i<news_url[a].length;i++){
						u.add(news_url[a][i]);
					}
				}else{
					u.add(news_url[a][b]);
				}
				//				Log.i("test","a"+a+"b"+b+" : "+news_url[a].length);

				callList(1);
			}
		});

	}


	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		//return super.onKeyDown(keyCode, event);
		if (keyCode == KeyEvent.KEYCODE_BACK&&event.getRepeatCount()==0)
		{
			AlertDialog.Builder bld = new AlertDialog.Builder(this);
			bld.setTitle("종료");
			bld.setMessage("종료하시겠습니까?");
			bld.setPositiveButton("예", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					moveTaskToBack(true);
					stopService(new Intent("org.cherry.namespace.mymp3"));
					finish();
				}
			});
			bld.setNegativeButton("아니오",null);
			bld.show();
			return true; 
		}
		return super.onKeyDown(keyCode, event);
	}




	void callList(int i){
		showDialog(DID);
		data = new ArrayList<List>();
		final int key = i;

		Thread thread = new Thread(){
			public void run(){

				switch (key) {
					case 1 ://rss 가져오기
						if(u.size()>1){
							for(int cnt=0;cnt<u.size();cnt++){
								MyParsing p = new MyParsing(u.get(cnt));
								ArrayList<List> getData = p.getAllData();
								data.add(new List(cat[cnt], null, "", null));
								for(int i=0;i<getData.size();i++){
									data.add(getData.get(i));
								}
							}
						}else{
							MyParsing p = new MyParsing(u.get(0));
							data = p.getData();
						}
						break;

					case 2 ://db 가져오기 				
						db.open();

						Cursor c = db.cursor("SELECT * FROM my_news ORDER BY _id DESC");

						c.moveToFirst();
						while(c.isAfterLast() == false){
							data.add(new List(c.getString(1),c.getString(2),c.getString(3),c.getString(4)));
							Log.i("test",c.getString(1)+","+c.getString(2)+","+c.getString(3)+","+c.getString(4));
							c.moveToNext();
						}

						c.close();
						if(db != null)	db.close();

						if(data.size()==0){
							data.add(new List("내 스크랩이 없습니다.", null, "", "뉴스보기를 눌러주세요."));
						}else{
						}

						break;

				}

				adapter = new MyAdapter(MainActivity.this, data); 

				Message msg = handler.obtainMessage(WHAT);
				handler.sendMessage(msg);

			};
		};

		thread.start();

	}

	protected Dialog onCreateDialog(int id){
		ProgressDialog d = new ProgressDialog(this);
		switch(id){
			case DID:
				d.setMessage("Loding...");
				d.setIndeterminate(true);
				d.setCancelable(true);
				return d;
		}
		return d;
	}

}
